import json

from sshcon import sshClient


# 读取cityParams.json 文件，获取城市对应的 ssh 连接信息
def getCityClient(city, cityFilePath):
    # 读取 cityParams.json 文件
    with open(cityFilePath, 'r', encoding='utf-8') as f:
        cityParams = json.load(f)
    # 获取城市对应的 ssh 连接信息
    cityList = cityParams.get('data')
    # 遍历cityList，找到 city 名称是传入的
    sshClientInfo = {}
    for item in cityList:
        if item.get('city') == city:
            sshClientInfo = item
            break
    print(sshClientInfo)

    return sshClientInfo


def getSSHClient(sshClientInfo):
    if not sshClientInfo:
        return None
    ssh = None
    if sshClientInfo.get('ssh_key_file') and sshClientInfo.get('ssh_password'):
        # 使用密钥和密码进行登录
        ssh = sshClient.getSSHClientByPem(sshClientInfo.get('ssh_host'), sshClientInfo.get('ssh_port'),
                                          sshClientInfo.get('ssh_username'), sshClientInfo.get('ssh_key_file')
                                          , sshClientInfo.get('ssh_password'))
    elif sshClientInfo.get('ssh_key_file'):
        # 使用密钥进行登录
        ssh = sshClient.getSSHClientByPem(sshClientInfo.get('ssh_host'), sshClientInfo.get('ssh_port'),
                                          sshClientInfo.get('ssh_username'),
                                          sshClientInfo.get('ssh_key_file'))
    else:
        # 使用密码进行登录
        ssh = sshClient.getSSHClientByPassword(sshClientInfo.get('ssh_host'), sshClientInfo.get('ssh_port'),
                                               sshClientInfo.get('ssh_username'), sshClientInfo.get('ssh_password'))
    return ssh


def connect(city, cityFilePath):
    sshclientInfo = getCityClient(city, cityFilePath)
    ssh = getSSHClient(sshclientInfo)
    return ssh
